package com.axxc.jpa.task.rabbitmsg.provider;

import java.util.Date;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.axxc.jpa.entity.DeadLetterMsgEntity;
import com.axxc.jpa.entity.StudentEntity;
import com.axxc.jpa.out.common.constant.RabbitMQConstant;

/**
 * @ClassName: RabbitMqStringMsgProviderTask
 * @Description: 延迟队列消息测试
 * @author xxc
 * @date 2018年8月28日22:06:46
 * @see https://blog.csdn.net/i_vic/article/details/72742277
 */
@Component
public class RabbitMqDelayStringMsgProviderTask {

	@Autowired
	private AmqpTemplate rabbitTemplate;

	@Async
	@Scheduled(cron = "0 0/5 * * * *")
	public void testDelayMsg() {

		// TODO 包装消息为含下一个队列名称及内容体
		DeadLetterMsgEntity<String> entity = new DeadLetterMsgEntity<>();
		StudentEntity e = new StudentEntity();
		e.setName("熊骑士");
		e.setAge(18);
		e.setSex((byte) 0);
		e.setCreateTime(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
		entity.setContent(e.toJsonString());
		entity.setExchangeName(RabbitMQConstant.DEFAULT_EXCHANGE);
		entity.setQueueName("hello");
		entity.setTime(30000L);// TimeUnit 可以使用时间单位类灵活换算
		// TimeUnit timeUnit = TimeUnit.DAYS;
		// timeUnit.toMillis(30);
		// 以上应提取为参数传入

		MessagePostProcessor postProcessor = new MessagePostProcessor() {

			@Override
			public Message postProcessMessage(Message message) throws AmqpException {
				message.getMessageProperties().setExpiration("30000");// 60秒//此处应该为动态参数传入
				return message;
			}
		};
		this.rabbitTemplate.convertAndSend(RabbitMQConstant.DEFAULT_EXCHANGE,
				RabbitMQConstant.DEFAULT_DEAD_LETTER_QUEUE_NAME, JSONObject.toJSONString(entity), postProcessor);

	}
}
